package com.epam.qanda.web.servlet.logged;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.epam.qanda.db.model.User;
import com.epam.qanda.db.model.UserCategory;
import com.epam.qanda.db.service.UserCategoryService;

public class SubscribeCategoryServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		User user = (User) request.getSession().getAttribute("user");
		String[] addCategory = request.getParameterValues("addCategory");
		String[] removeCategory = request.getParameterValues("removeCategory");

		UserCategoryService service = new UserCategoryService();
		if (removeCategory != null && removeCategory.length > 0) {
			List<UserCategory> DBData = service.getUserCategories(user.getId());
			for (String s : removeCategory) {
				for (int i = 0; i < DBData.size(); i++) {
					if (DBData.get(i).getCategoryId() == Integer.parseInt(s)
							&& DBData.get(i).getUserId() == user.getId()) {
						service.delete(DBData.get(i).getId());
					}
				}
			}
		}
		if (addCategory != null && addCategory.length > 0) {
			for (String s : addCategory) {
				UserCategory element = new UserCategory();
				element.setUserId(user.getId());
				element.setCategoryId(Integer.parseInt(s));
				service.create(element);
			}
		}
		response.sendRedirect(request.getHeader("Referer"));
	}

}
